<?php

namespace app\common\model;

use MongoDB\BSON\ObjectId;
use app\common\lib\ZhyxMongo;
use catcher\exceptions\FailedException;
use app\common\model\search\FollowHistorySearch;
use think\db\exception\DbException;
use think\Paginator;

class FollowHistory extends BaseModel
{
    use FollowHistorySearch;

    protected $name = "follow_history";

    public function setFollowIdAttr($value, $data)
    {
        return new ObjectId($value);
    }

    public function setTaskIdAttr($value, $data)
    {
        return new ObjectId($value);
    }

    public function getDiagnosisAttr($value, $data)
    {
        if (isset($value['diseaseName'])) {
            return $value['diseaseName'];
        }
        return $value;
    }

    /**
     * 添加数据
     * @param array $param
     * @return string
     */
    public function addData(array $param): string
    {
        //添加时销毁自带的主键id
        unset($param['id']);
        return $this->save($param);
    }

    /**
     * 更新数据
     * @param array $param
     * @return bool
     */
    public function saveData($id, array $param): bool
    {
        $model = self::find($id);
        return $model->save($param);
    }

    /**
     * 删除
     * @param array $id
     * @return bool
     */
    public function delData(array $id): bool
    {
        return self::destroy($id);
    }

    /**
     * 获取条件匹配的数据
     * @param array $where 条件
     * @param string $field 字段
     * @return array
     */
    public function getConditionData(array $where = [], string $field = "*"): array
    {
        return $this->field($field)->where($where)->select();
    }

    /**
     * 获取患者随访历史记录
     *
     * @param string $patientId 患者patientId
     * @param string $task_id 随访计划id
     * @param int $type 类型 1 患者入口，2 随访入口
     * @return Paginator
     */
    public function getPatientFollowHistory(int $type, string $patientId, string $task_id = ''): Paginator
    {
        $where = [];
        $where[] = ['patientId', '=', $patientId];
        #$where[] = ['mode', 'in', [1,2,3,4]];
        if ($type == 2 && !empty($task_id)) {
            $where[] = ['task_id', '=', new ObjectId($task_id)];
        }

//        $user = $this->getUserIds();
//
//        if ($user) {
//            $users = array_map(function ($v) { return (int)$v; }, $user);
//            $where[] = ['staffId', 'in', $users];
//        }

        //随访方式
        $mode = [1 => '微信', 2 => '短信', 3 => '微信/短信', 4 => '电话'];

        $field = 'id,mode,pid,pushtime,pushdatetime,staffName,mode,status,resultName,diagnosis,audio,taskname,projectName,projectId,answer_id,status,patientId';

        return $this->mongoSearch([], [], ['patientId','type', 'task_id'])
            ->field($field)
            ->where($where)
            ->order(['pushtime' => -1, 'pushdatetime' => -1])
            ->paginate($this->pageLimit)
            ->each(function ($item, $key) use ($mode) {
                $patient = (new PatientInfo())->where('id', $item['pid'])->field('name,medicalRecordsNo')->find();
                $item["number"] = $key + 1;
                $item["followTime"] = $item['pushtime'];
                $item["pushdatetime"] = isset($item['pushdatetime'])&&!empty($item['pushdatetime'])?$item['pushdatetime']:$item['pushtime'];
                $item["wechatStatus"] = $item['mode'] == 1 ? '已发送' : '';;
                $item["smsStatus"] = $item['mode'] == 2 ? '已发送' : '';
                $item["mode"] = $mode[$item['mode']]??'系统随访';
                $item["resultName"] = $item['resultName'] ?? '';
                $item["diagnosis"] = $item["diagnosis"] ?? '';
                $item['audio'] = $item['audio']?request()->domain() . request()->server('port') . $item['audio'] : '';
                $item["name"] = $patient["name"]??'';
                $item["medicalRecordsNo"] = $patient["medicalRecordsNo"]??'';
                $item["taskname"] = $item["taskname"]??'系统随访';
                switch ($item['status']) {
                    case 2:
                        $item["followStatus"] = '已完成';
                        break;
                    case 3:
                        $item["followStatus"] = '暂存';
                        break;
                    case 1:
                    default:
                        $item["followStatus"] = '未完成';
                        break;
                }
                return $item;
            });
    }

    /**
     * 条件获取数据
     * @param array $where 查询条件
     * @param string $field 字段
     */
    public function getOneData(array $where = [], string $field = "*", $sort = "desc")
    {
        return $this->where($where)->field($field)->order('created_at', $sort)->find();
    }

    /**
     * mongo追加新元素到array类型字段
     * @param string $id 主键
     * @param string $field 字段
     * @param array $data 参数
     * @return bool
     */
    public function appToData(string $id, string $field, array $data = []): bool
    {
        try {
            ZhyxMongo::getInstance()->setCollection($this->name)->updateMany(["_id" => new ObjectId($id)], ['$push' => [$field => ['$each' => $data]]]);
            return true;
        } catch (\Exception $exception) {
            throw new FailedException($exception->getMessage());
        }
    }

    /**
     * 获取患者随访记录
     * @param string $patientId 患者id
     * @return Paginator
     */
    public function getRecord(string $patientId): Paginator
    {
        $where = [];
        $where[] = ['patientId', '=', $patientId];
        $where[] = ['mode', 'in', [2,3]];
        return  $this->field('id,projectId,projectName,answer_id,staffName,staffDoctorCode,pushtime,status,taskname,patientId')
                    ->where($where)
                    ->order('created_at', 'desc')
                    ->paginate($this->pageLimit)
                    ->each(function ($item, $key) {
                        $item['follow_staff'] = $item['staffName'].'('.$item['staffDoctorCode'].')';
                        if (!isset($item['staffDoctorCode'])) {
                            $item['follow_staff'] = '自动随访';
                        }
                    });
    }

    /**
     * 获取列表
     * @param array $where
     * @param string $field
     * @param array $outField
     * @param string $order
     * @return Paginator
     */
    public function getDataList(array $where=[], string $field='*', array $outField=[], string $order='pushtime'): Paginator
    {
        try {
            return $this->mongoSearch([], [], $outField)
                ->where($where)
                ->field($field)
                ->order($order, -1)
                ->cache(true, 3600)
                ->paginate($this->pageLimit);
        } catch (DbException $e) {
            throw new FailedException($e->getMessage());
        }
    }
}
